<?php
namespace app\admin\service;


use app\model\Addons;
use app\model\AuthRule;

/**
 * Class AddonsService
 * @package app\service
 */
class AddonsService extends CommonService
{
    /**
     *
     */
    public static function getList()
    {
        $result = [];
        $paths = glob(app()->getRootPath() . 'addons/*', GLOB_ONLYDIR);
        $addons = array_map('basename', $paths);

        $addonsNames = implode(',', $addons);
        $addonList = Addons::getList([['keyname', 'in', $addonsNames]]);
        $addonList = array_column($addonList, null, 'keyname');

        foreach ($addons as $key => $addon)
        {
            if (empty($addonList[$addon]))
            {
                $result[$key]['id'] = 0;
                $result[$key]['keyname'] = $addon;
                $result[$key]['type'] = 0;
                $result[$key]['title'] = $addon;
                $result[$key]['desc'] = '暂无描述';
                $result[$key]['status'] = 2;
                $result[$key]['create_time'] = 0;
            } else {
                $result[$key] = $addonList[$addon];
            }
        }
        return $result;
    }

    /**
     * @desc 安装插件
     * @param $keyname 插件标识
     * @return bool
     */
    public static function install($keyname)
    {
        // 检查是否已经存在该插件
        $addon = Addons::getOne(['keyname' => $keyname, 'status' => 1]);
        if (!empty($addon))
        {
            self::error(401, '该插件已安装!');
        }

        // 检查插件初始化文件
        $baseDir = rootPath() . '/addons/' . $keyname;
        $initFile = $baseDir . '/config/init.php';

        if (file_exists($initFile))
        {
            $conf = require_once $initFile;

            $addonData = [
                'keyname' => $keyname,
                'type' => $conf['type'],
                'tag' => $conf['tag'],
                'title' => $conf['title'],
                'desc' => $conf['desc'],
                'status' => 1,
                'create_time' => time()
            ];
            $addon = Addons::getOne(['keyname' => $keyname]);
            if (!empty($addon))
            {
                Addons::updateOne($addonData, ['keyname' => $keyname]);
            } else {
                Addons::addOne($addonData);
            }
            if (!empty($conf['menu']))
            {
                // 删除已经存在的菜单
                $existMenus = AuthRule::getList(['addon' => $keyname]);
                $menuIds = array_column($existMenus, 'id');
                AuthRule::deleteByIds($menuIds);

                self::createAddonMenu($conf['menu'], $keyname);
            }
        } else {
            self::error(401, '安装失败!');
        }
        return true;
    }

    /**
     * @desc 插件卸载
     * @param $keyname
     * @return bool
     */
    public static function uninstall($keyname)
    {
        // 删除已经存在的菜单
        $existMenus = AuthRule::getList(['addon' => $keyname]);
        $menuIds = array_column($existMenus, 'id');
        AuthRule::deleteByIds($menuIds);

        Addons::updateOne(['status' => 2], ['keyname' => $keyname]);
        return true;
    }

    /**
     * @desc 插入插件菜单
     * @param $menu
     * @param $keyname
     */
    public static function createAddonMenu($menu, $keyname)
    {
        foreach ($menu as $val)
        {
            // 1级菜单
            $lv = $val['lv'];
            $menuData = self::formatCreateMenuData($val, $keyname, $val['pid'], $lv);
            $pid = AuthRule::addOne($menuData, true);
            if (!empty($val['sub_list']))
            {
                // 二级菜单
                foreach ($val['sub_list'] as $v)
                {
                    $menuData2 = self::formatCreateMenuData($v, $keyname, $pid, $lv + 1);
                    $pid2 = AuthRule::addOne($menuData2, true);
                    if (!empty($v['sub_list']))
                    {
                        // 三级菜单
                        foreach ($v['sub_list'] as $vv)
                        {
                            $menuData3 = self::formatCreateMenuData($vv, $keyname, $pid2, $lv + 2);
                            $pid3 = AuthRule::addOne($menuData3, true);
                            if (!empty($vv['sub_list']))
                            {
                                // 四级菜单
                                foreach ($vv['sub_list'] as $vvv)
                                {
                                    $menuData4 = self::formatCreateMenuData($vv, $keyname, $pid3, $lv + 3);
                                    AuthRule::addOne($menuData4, true);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * @desc 整理菜单数据
     * @param $data
     * @param $keyname
     * @param $pid
     * @param $lv
     * @return mixed
     */
    public static function formatCreateMenuData($data, $keyname, $pid, $lv)
    {
        $menuData['addon'] = $keyname;
        $menuData['title'] = $data['title'];
        $menuData['pid'] = $pid;
        $menuData['lv'] = $lv;
        $menuData['url'] = $data['url'];
        $menuData['icon'] = $data['icon'];
        $menuData['status'] = $data['status'];
        $menuData['sort'] = $data['sort'];
        $menuData['desc'] = $data['desc'];
        $menuData['is_control'] = $data['is_control'];
        return $menuData;
    }
}